package org.devf.fork.imsimulator.socket;

import cn.hutool.core.lang.Assert;
import org.devf.fork.imsimulator.model.HttpConstant;

import java.util.Optional;

/**
 * TcpClientFactory related
 *
 * @author wanghuafu
 * @since 0.1 2023/9/12
 */
public class TcpClientFactory {
    private static DefaultTcpClient defaultTcpClient;

    /**
     * tcp单例模式
     *
     * @return 客户端
     */
    public static synchronized DefaultTcpClient getDefault() {
        if (null == defaultTcpClient || defaultTcpClient.isHadDestroy()) {
            defaultTcpClient = new DefaultTcpClient(HttpConstant.Host.serverHost,
                    Integer.parseInt(HttpConstant.Host.socketPort));
            boolean isOk = defaultTcpClient.create();
            Assert.isTrue(isOk, "创建socket连接异常!!");
        }

        return defaultTcpClient;
    }

    public static Optional<DefaultTcpClient> getDefaultTcpClient() {
        return Optional.ofNullable(defaultTcpClient);
    }
}
